<template>
    <div>
    <dl>
      <dt class="flex">
        <span class="">最新用户</span>
        <form class="flex grow justify-end gap-2" @submit.prevent="handlerSubmit">
          <input type="text" name="title" v-model="title" class=" border">

          <button type="submit">搜索</button>
        </form>
      </dt>
      <dd v-for="user in users" class="flex border-b gap-x-2">
        <span class="grow">{{ user.userName }}</span>
        <span><button>编辑</button></span>
      </dd>
      <!-- 分页 -->
      <dd class="pt-2 pb-1">
        <ul class="flex justify-end gap-1 [&>li]:p-1 [&>li]:border [&>li]:cursor-pointer">
          <!-- 上一页按钮 -->
          <li :class="{ 'bg-gray-200': currentPage === 1 }" @click="handlerPage(currentPage - 1)"
            :disabled="currentPage === 1">
            <NuxtLink :to="`/users?page=${currentPage - 1}&title=${title}`">上一页</NuxtLink>
            <!-- 上一页 -->
          </li>
          <!-- 页码循环 -->
          <li v-for="page in displayedPages" :key="page" :class="{ 'bg-gray-200': page === currentPage }"
            @click="handlerPage(page)">
            <NuxtLink :to="`/users?page=${page}&title=${title}`">
              {{ page }}    
            </NuxtLink>
            <!-- {{ page }} -->
          </li>
          <!-- 下一页按钮 -->
          <li :class="{ 'bg-gray-200': currentPage === totalPages }" @click="handlerPage(currentPage + 1)"
            :disabled="currentPage === totalPages">
            <NuxtLink :to="`/users?page=${currentPage + 1}&title=${title}`">下一页</NuxtLink>
            <!-- 下一页 -->
          </li>
        </ul>
      </dd>
    </dl>
  </div>
</template>

<script setup lang="ts">
import { UsersApi } from '~/api';

let route = useRoute();
console.log("query:",route.query)
let query_title = route.query.title?.toString()??'';
let query_page = parseInt(route.query.page?.toString()??'1')

let title = ref('');

let currentPage = ref(query_page); // 当前页码
let totalPages = ref(1); // 总页数
const page_display_count = ref(10); // 限制显示的页码数量

let {data:res} = await useAsyncData("users", () => UsersApi.getUsers(query_title,query_page));
let users = ref(res.value?.data.items||[]);
totalPages.value = res.value?.data.pages||1;
page_display_count.value = res.value?.data.pageSize||10;



async function fetchData(page = 1) {
  try {
    console.log("todosview,", "fetchTodos");
    let res = await UsersApi.getUsers(title.value, page)
    users.value = res.data.items;
    totalPages.value = res.data.pages;
    page_display_count.value = res.data.pageSize;
  } catch (error) {
    console.error('获取最新用户失败:', error);
  }
}

//handlerSubmit
async function handlerSubmit(e: Event) {
  e.preventDefault();
  currentPage.value = 1; // 搜索时重置到第一页
  await fetchData();
}



//handlerPage
async function handlerPage(page: number) {
  if (page < 1 || page > totalPages.value) return;
  currentPage.value = page;
  await fetchData(page);
}

// 计算要显示的页码范围
const displayedPages = computed(() => {
  let startPage = Math.max(currentPage.value - Math.floor(page_display_count.value / 2), 1);
  let endPage = startPage + page_display_count.value - 1;
  if (endPage > totalPages.value) {
    endPage = totalPages.value;
    startPage = Math.max(endPage - page_display_count.value + 1, 1);
  }
  return Array.from({ length: endPage - startPage + 1 }, (_, i) => startPage + i);
});

</script>

<style scoped>

</style>